package xcraft.xserver;

import java.io.StringWriter;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jersey.spi.inject.Inject;

/**
 * 
 * @author AlexM
 *
 */
public class ResourceBase {

    private static final Logger log = LoggerFactory.getLogger(ResourceBase.class);

    /**
     * This field holds injected Jackson {@link ObjectMapper}.
     */
    @Inject("objectMapper")
    protected ObjectMapper objectMapper;

    /**
     * Returns JSON representation of object.
     * 
     * @param token
     *            String
     * @return JSON representation of object.
     */
    protected String getJSON(Object obj) {
        if (obj == null) {
            return "{}";
        }

        try {
            StringWriter buffer = new StringWriter();
            objectMapper.writeValue(buffer, obj);
            return buffer.toString();
        } catch (Exception ex) {
            log.debug("Failed to convert object to JSON '{}' ", obj);
            throw new XException(ex);
        }
    }

}
